package me.helllp.bootman.back.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Import;

import me.helllp.bootman.back.config.shiro.JwtAuthcFilter;
import me.helllp.bootman.back.config.shiro.JwtRealm;
import me.helllp.bootman.back.config.shiro.ShiroManager;
import me.helllp.bootman.back.services.impl.TokenServiceJwtImpl;

@Configuration
@Import(ShiroManager.class)
public class ShiroConfiguration{

	@Bean(name = "realm")
	@DependsOn("lifecycleBeanPostProcessor")
	@ConditionalOnMissingBean
	public Realm realm() {
		return new JwtRealm(new TokenServiceJwtImpl());
	}
	
	@Bean(name = "shiroFilter")
	@DependsOn("securityManager")
	@ConditionalOnMissingBean
	public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultSecurityManager securityManager, Realm realm) {
		securityManager.setRealm(realm);

		ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
		shiroFilter.setSecurityManager(securityManager);

		/**
		 * 设置配置数据：anon,statelessAuthc
		 */
		Map<String, String> filterDef = new LinkedHashMap<String, String>();

		filterDef.put("/user/no001", "anon");
		filterDef.put("/user/no002", "statelessAuthc");
		filterDef.put("/user/test", "statelessAuthc[abc]");
		
		filterDef.put("/druid/**", "anon");
		
		filterDef.put("/**", "anon");
		
		shiroFilter.setFilterChainDefinitionMap(filterDef);

		// 设置过滤器：进行权限过滤
//		shiroFilter.getFilters().put("userAuthc", getUserAuthc());
		shiroFilter.getFilters().put("statelessAuthc", getAuthcFilter());
		// 需要进行多个角色校验的时候：statelessRoles[role1,role2]
//		shiroFilter.getFilters().put("statelessRoles", getRoleFilter());


		return shiroFilter;
	}

	@Bean(name = "statelessAuthc")
	@ConditionalOnMissingBean
	public JwtAuthcFilter getAuthcFilter() {
		return new JwtAuthcFilter();
	}
}
